// pages/campShop/campShop.js
const camp = require("../../api/camp");
const second = require("../../api/second")
const {
  baseURL
} = require("../../utils/request")
Page({
  /**
   * 页面的初始数据
   */
  data: {
    oss_url: baseURL,
    userId: wx.getStorageSync('userInfo').userId,
    goodsList: [], //商品列表
    cartList: [], //购物车列表
    campList: [], //营地列表
    active: 0,
    cartLength: 0,
    showCart: false,
    amount: 0
  },

  sumAmount(){
    var cartList = this.data.cartList;
    var amount = 0;
    for (let i = 0; i < cartList.length; i++) {
      const item = cartList[i];
      amount += item.num * item.goodsPrice;
    }
    this.setData({
      amount: amount,
      cartLength: cartList.length
    })
    wx.setStorageSync('cartList-' + this.data.campId, this.data.cartList)
  },

  // 当在商品数量变化时
  onStepperChange(event) {
    console.log("onStepperChange event",event);
    let index = event.currentTarget.dataset.index;
    var goodsList = this.data.goodsList;
    var cartList = this.data.cartList;
    goodsList[index].num = event.detail;
    cartList.push(goodsList[index]);
    const uniqueCartList = cartList.filter((item,index,self)=>{
      return index === self.findIndex(obj => obj.goodsId === item.goodsId);
    })
    const finalList = uniqueCartList.filter(item => item.num > 0);
    this.setData({
      goodsList: goodsList,
      cartList: finalList,
      cartLength: finalList.length
    })
    this.sumAmount();
  },

  // 当在购物车数量变化时
  onCartStepperChange (event) {
    console.log("onCartStepperChange event", event);
    let index = event.currentTarget.dataset.index;
    var cartList = this.data.cartList;
    cartList[index].num = event.detail;
    const uniqueCartList = cartList.filter((item, index, self) => {
      return item.num > 0;
    });
    // 当购物车中的数量改变时，同步商品的下标
    var goodsList = this.data.goodsList;
    for (let j = 0; j < goodsList.length; j++) {
      if (cartList[index].goodsId == goodsList[j].goodsId) {
        goodsList[j].num = cartList[index].num;
        break;
      }
    }
    this.setData({
      cartList: uniqueCartList,
      goodsList: goodsList
    })
    this.sumAmount();
  },

  // 打开购物车
  onShowCart(){
    this.setData({ showCart: true });
  },

  // 关闭钩吻车
  onCloseCart() {
    this.setData({ showCart: false });
  },

  onClickButton(event){
    this.addOrder();
  },
  // 订单添加方法
  addOrder() {
    second.addOrder({
      orderDetails:this.data.cartList,
      userId: this.data.userId,
      campId: this.data.campId,
      total:this.data.amount,
    }).then((res) => {
      console.log(res);
      if (res.code === 200) {
        wx.showToast({
          title: '租赁成功',
          icon: 'none',
          duration: 1500
        })
        wx.setStorageSync('cartList-'+this.data.campId, [])
      }
    })
  },
  // 商品搜索
  searchGoods(e) {
    this.setData({
      goodsName: e.detail,
    });
    console.log("要搜索的goodsName为：", this.data.goodsName);
    let query = {
      goodsName: this.data.goodsName,
      campId: this.data.campId
    }
    this.getGoodsList(query);
  },

  // 左侧导航栏切换事件
  onChange(event) {
    this.setData({
      campId: this.data.campList[event.detail].campId
    })
    let query = {
      campId: this.data.campId
    }
    this.getGoodsList(query);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getAppointmentByUserId();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 获取营地预约数据
   */
  getAppointmentByUserId() {
    camp.appointmentCampList(this.data.userId).then(res => {
      if (res.code == 200) {
        this.setData({
          campList: res.data,
          campId: res.data[0].campId
        })
      }
      if (res.data.length < 0) {
        return;
      }
      let query = {
        campId: res.data[0].campId
      }
      this.getGoodsList(query);
    })
  },
  // 获取商品列表
  getGoodsList(query) {
    second.goodsList(query).then(res => {
      console.log(res.data, "营地商品列表")
      if (res.code == 200) {
        var _goodsList = res.data
        for (let i = 0; i < _goodsList.length; i++) {
          _goodsList[i].num = 0;
        }
        res.data.forEach(item => {
          // 判断有没有逗号 有就是多张图片 取第一张图片
          if (item.imageUrl.indexOf(',') != -1) {
            item.imageUrls = item.imageUrl.split(',');
            item.imageUrl = item.imageUrl[0];
          }
        });
        console.log("_goodsList",_goodsList)
        this.setData({
          goodsList: _goodsList
        });
        // 根据购物车缓存数据，调整商品右下角下标
       this.setCartList();
      }
    });
  },

  // 从本地存储中查询购物车数据
  setCartList () {
    var cartList = wx.getStorageSync('cartList-' + this.data.campId)
    if (cartList && cartList.length > 0) {
      this.setData({
        cartList: cartList
      })
    } else {
      this.setData({
        cartList: []
      })
    }
    this.sumAmount();
    this.setGoodsNum();
  },
  
  // 设置商品已经加入购物车的数量
  setGoodsNum() {
    var cartList = this.data.cartList;
    var goodsList = this.data.goodsList;
    for (let i = 0; i < cartList.length; i++) {
      const cartItem = cartList[i];
      for (let j = 0; j < goodsList.length; j++) {
        const goodsItem = goodsList[j];
        if (cartItem.goodsId == goodsItem.goodsId) {
          goodsList[j].num = cartItem.num;
          break;
        }
      }
    }
    this.setData({
      goodsList: goodsList
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})